package conceptmaniax.hotelapp.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import conceptmaniax.hotelapp.config.Constants;
import conceptmaniax.hotelapp.enums.Language;
import conceptmaniax.hotelapp.managers.RequestManager;
import conceptmaniax.hotelapp.util.GeneralUtils;

public class CheckinActivity extends Activity {
	private Language language;
	private String name;
	private String action;
    private Button showInfo;
    private Button showServices;
    private Button showGuide;
    private Button showBooking;
    private Button requests;
    private ScrollView homeScreen;
    private TableLayout callout;
    private ListView callout_list;
	private TextView counter;

    private int hours;
    private int minute;
    private int tag=0;
    SparseArray<EditText> editTexts = new SparseArray<EditText>();
	
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		action = getIntent().getExtras().getString("action");
		if (action.equals("checkin")) {
			tag=1;
			setContentView(R.layout.check_in);
		}
		else if (action.equals("checkout"))
			setContentView(R.layout.check_out);
		
		language = GeneralUtils.getLanguage(this);
		
		//Go back to HomePage Button
		final Button go_to_home = (Button) findViewById(R.id.homeButton);
			go_to_home.setOnClickListener(new View.OnClickListener() {
			public void onClick(final View view) {
		    	final Intent homePageIntent = new Intent(Constants.HOMEPAGE_ACTIVITY);
		    	startActivity(homePageIntent);
			}
		});
		
			// Parse String array from previous intent
			name = getIntent().getExtras().getString("name");
			
			final TextView serviceTitle = (TextView)findViewById(R.id.service_title);
	     	serviceTitle.setText(name);
	     	
	   		final Button submit = (Button) findViewById(R.id.submit);
			showInfo = (Button) findViewById(R.id.hotel_button);
			showServices = (Button) findViewById(R.id.services_button);
			showGuide = (Button) findViewById(R.id.guide_button);
			showBooking = (Button) findViewById(R.id.booking_button);
			homeScreen = (ScrollView) findViewById(R.id.form_main_layout);
	 		requests = (Button) findViewById(R.id.requestsButton);
			callout = (TableLayout)findViewById(R.id.callout_table);
			callout_list = (ListView)findViewById(R.id.callout_listview);
			counter = (TextView) findViewById(R.id.counter);
			
	     	if (tag == 1 || tag == 2) {    
	     		final EditText txt_surname= (EditText) findViewById(R.id.surname);
	     		final EditText txt_name = (EditText) findViewById(R.id.name);
	     		final EditText txt_profession = (EditText) findViewById(R.id.profession);
	     		final EditText txt_nationality= (EditText) findViewById(R.id.nationality);
	     		final EditText txt_passport = (EditText) findViewById(R.id.passport);
	     		final EditText txt_issue = (EditText) findViewById(R.id.issue_date);
	     		final EditText txt_birth = (EditText) findViewById(R.id.birth_date);
	     		editTexts.put(1, txt_surname);
	     		editTexts.put(2, txt_name);
	     		editTexts.put(3, txt_passport);
	     		editTexts.put(4, txt_issue);
	     		editTexts.put(5, txt_birth);

	     		txt_surname.setOnEditorActionListener(new OnEditorActionListener() {
    				@Override
    				public boolean onEditorAction(TextView v, int keyCode,
    						KeyEvent event) {
    					if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {               
    		   		           InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    		   		           im.hideSoftInputFromWindow(homeScreen.getWindowToken(), 0);
    		   		           return true;
    		   		        }	
    					return false;
    				}
    	   		});
     			
	     		txt_name.setOnEditorActionListener(new OnEditorActionListener() {
    				@Override
    				public boolean onEditorAction(TextView v, int keyCode,
    						KeyEvent event) {
    					if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {               
    		   		           InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    		   		           im.hideSoftInputFromWindow(homeScreen.getWindowToken(), 0);
    		   		           return true;
    		   		        }		
    					return false;
    				}
    	   		});
     			
	     		txt_profession.setOnEditorActionListener(new OnEditorActionListener() {
    				@Override
    				public boolean onEditorAction(TextView v, int keyCode,
    						KeyEvent event) {
    					if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {               
    		   		           InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    		   		           im.hideSoftInputFromWindow(homeScreen.getWindowToken(), 0);
    		   		           return true;
    		   		        }	
    					return false;
    				}
    	   		});
     			
	     		txt_nationality.setOnEditorActionListener(new OnEditorActionListener() {
    				@Override
    				public boolean onEditorAction(TextView v, int keyCode,
    						KeyEvent event) {
    					if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {               
    		   		           InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    		   		           im.hideSoftInputFromWindow(homeScreen.getWindowToken(), 0);
    		   		           return true;
    		   		        }			
    					return false;
    				}
    	   		});
     			
	     		txt_passport.setOnEditorActionListener(new OnEditorActionListener() {
    				@Override
    				public boolean onEditorAction(TextView v, int keyCode,
    						KeyEvent event) {
    					if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {               
    		   		           InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    		   		           im.hideSoftInputFromWindow(homeScreen.getWindowToken(), 0);
    		   		           return true;
    		   		        }		
    					return false;
    				}
    	   		});
     			
	     		txt_issue.setOnFocusChangeListener(new View.OnFocusChangeListener() {
					@Override
					public void onFocusChange(View v, boolean hasFocus) {
		 				if (hasFocus) {
		 					disableSoftInputFromAppearing(txt_issue);
							tag=1;
		     				setdate(v);	
		 				}
					}
					
				});
	     		
	     		txt_birth.setOnFocusChangeListener(new View.OnFocusChangeListener() {
					@Override
					public void onFocusChange(View v, boolean hasFocus) {
		 				if (hasFocus) {
			 				disableSoftInputFromAppearing(txt_birth);
			 				tag=2;
		     				setdateOnly(v);
		 				}
					}
				});

     		} else if (tag==0) {	     
	     		final EditText txt_card_number= (EditText) findViewById(R.id.card_no);
	     		final EditText txt_card_type = (EditText) findViewById(R.id.card_type);
	     		final EditText txt_address = (EditText) findViewById(R.id.address);
     			final EditText txt_expires = (EditText) findViewById(R.id.expires);
				txt_expires.setInputType(InputType.TYPE_NULL);
	     		editTexts.put(6, txt_card_number);
	     		editTexts.put(7, txt_card_type);
	     		editTexts.put(8, txt_address);
	     		editTexts.put(9, txt_expires);

     			txt_card_number.setOnEditorActionListener(new OnEditorActionListener() {
    				@Override
    				public boolean onEditorAction(TextView v, int keyCode,
    						KeyEvent event) {
    					if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {               
    		   		           InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    		   		           im.hideSoftInputFromWindow(homeScreen.getWindowToken(), 0);
    		   		           return true;
    		   		        }					
    					return false;
    				}
    	   		});
   		
     			txt_card_type.setOnEditorActionListener(new OnEditorActionListener() {
    				@Override
    				public boolean onEditorAction(TextView v, int keyCode,
    						KeyEvent event) {
    					if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {               
    		   		           InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    		   		           im.hideSoftInputFromWindow(homeScreen.getWindowToken(), 0);
    		   		           return true;
    		   		        }					
    					return false;
    				}
    	   		});
     			
     			txt_address.setOnEditorActionListener(new OnEditorActionListener() {
    				@Override
    				public boolean onEditorAction(TextView v, int keyCode,
    						KeyEvent event) {
    					if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {               
    		   		           InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    		   		           im.hideSoftInputFromWindow(homeScreen.getWindowToken(), 0);
    		   		           return true;
    		   		        }					
    					return false;
    				}
    	   		});
     			
     			txt_expires.setOnFocusChangeListener(new View.OnFocusChangeListener() {
					@Override
					public void onFocusChange(View v, boolean hasFocus) {
		 				if (hasFocus) 
		 					setdateOnly(v);
					}
				});
     	}
			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
	     	
     		submit.setOnClickListener(new View.OnClickListener() {
     			@Override
     			public void onClick(View r) {
  				    final AlertDialog.Builder builder = new AlertDialog.Builder(CheckinActivity.this);
  					final AlertDialog dialog;
  					String close = getBaseContext().getString(R.string.close_en);
  					if (tag == 1 || tag == 2) {
     					if ((editTexts.get(1).getText().toString().trim().length() != 0) && (editTexts.get(2).getText().toString().trim().length() != 0) && (editTexts.get(3).getText().toString().trim().length() != 0)
     						&& (editTexts.get(4).getText().toString().trim().length() != 0) && (editTexts.get(5).getText().toString().trim().length() != 0)) {
 	     					builder.setTitle("Thank you");
 	     					builder.setMessage("Thank you very much!");
 	     					builder.setNegativeButton(close, new DialogInterface.OnClickListener() {
 	     						@Override
 	     						public void onClick(final DialogInterface dialog, final int which) {
 	     							dialog.cancel();
 	     						}
 	     					});
 	     					dialog = builder.create();
 	     					dialog.show();
     						final Intent HomepageIntent = new Intent(getBaseContext(),HomepageActivity.class);
     						startActivity(HomepageIntent);
     					} else {
 	     					builder.setTitle("Warning");
 	     					builder.setMessage("Please fill the required(*) fields");
 	     					builder.setNegativeButton(close, new DialogInterface.OnClickListener() {
 	     						@Override
 	     						public void onClick(final DialogInterface dialog, final int which) {
 	     							dialog.cancel();
 	     						}
 	     					});
 	     					dialog = builder.create();
 	     					dialog.show();
     					}
     				} else if (tag == 0) {
     							CheckBox accept_terms = (CheckBox) findViewById(R.id.accept_box);
		     					if (((editTexts.get(6).getText().toString().trim().length() != 0) && (editTexts.get(7).getText().toString().trim().length() != 0) && 
		     					   (editTexts.get(8).getText().toString().trim().length() != 0) && (editTexts.get(9).getText().toString().trim().length() != 0)) && accept_terms.isChecked()) {
		 	     					builder.setTitle("Thank you");
		 	     					builder.setMessage("Hope to see you again!");
		 	     					builder.setNegativeButton(close, new DialogInterface.OnClickListener() {
		 	     						@Override
		 	     						public void onClick(final DialogInterface dialog, final int which) {
		 	     							dialog.cancel();
		 	     						}
		 	     					});
		 	     					dialog = builder.create();
		 	     					dialog.show();
		     						final Intent HomepageIntent = new Intent(getBaseContext(),HomepageActivity.class);
		     						startActivity(HomepageIntent);
		     					} else if (((editTexts.get(6).getText().toString().trim().length() != 0) && (editTexts.get(7).getText().toString().trim().length() != 0) && 
				     					   (editTexts.get(8).getText().toString().trim().length() != 0) && (editTexts.get(9).getText().toString().trim().length() != 0)) && !accept_terms.isChecked()) {
				 	     					builder.setTitle("Warning");
				 	     					builder.setMessage("Please accept the terms");
				 	     					builder.setNegativeButton(close, new DialogInterface.OnClickListener() {
				 	     						@Override
				 	     						public void onClick(final DialogInterface dialog, final int which) {
				 	     							dialog.cancel();
				 	     						}
				 	     					});
		     						} else {
			        					builder.setTitle("Warning");
			 	     					builder.setMessage("Please fill the fields");
			 	     					builder.setNegativeButton(close, new DialogInterface.OnClickListener() {
			 	     						@Override
			 	     						public void onClick(final DialogInterface dialog, final int which) {
			 	     							dialog.cancel();
			 	     						}
			 	     					});
			 	     					dialog = builder.create();
			 	     					dialog.show();
			     					}
		     				}
     				}
     		});	
     		
     		requests.setOnClickListener(new View.OnClickListener() {
     			@Override
				public void onClick(View v) {
    				final Intent requestsIntent = new Intent(getBaseContext(), RequestListActivity.class);
    				startActivity(requestsIntent);	
     			}
			});
	}		
	@SuppressLint("NewApi")
	public static void disableSoftInputFromAppearing(EditText editText) {
	    if (Build.VERSION.SDK_INT >= 11) {
	        editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
	        editText.setTextIsSelectable(true);
	    } else {
	        editText.setRawInputType(InputType.TYPE_NULL);
	        editText.setFocusable(true);
	    }
	}
		
	public void setdate(View v) {
		final Dialog dialog = new Dialog(this);
	    dialog.setContentView(R.layout.date_picker);
	    dialog.setCancelable(true);
	    dialog.setTitle("");
	    dialog.show();
	    	    
	    TimePicker time_picker = (TimePicker) dialog.findViewById(R.id.timePicker1);
	    if (tag == 2 || tag == 0)
	    	time_picker.setVisibility(View.INVISIBLE);
	    
	    time_picker.setOnTimeChangedListener(new OnTimeChangedListener()
	    {
			@Override
	        public void onTimeChanged(TimePicker view, int hourOfDay, int minutes)
	        {
	            hours = hourOfDay;
	            minute = minutes;
	        }
	    });

	    final DatePicker date_picker = (DatePicker) dialog.findViewById(R.id.datePicker1);
	    Button btn = (Button) dialog.findViewById(R.id.buttondatetime);
	    btn.setOnClickListener(new OnClickListener()
	    {
	        public void onClick(View arg0)
	        {
	        	if (tag == 1) {
	        		EditText txt = (EditText) findViewById(R.id.issue_date);
		            String temp = "" + date_picker.getDayOfMonth() + "/" + (date_picker.getMonth() + 1) + "/"
		                    + date_picker.getYear()+", "+ hours + ":" +minute;
					try {
					    Date requestDate = new SimpleDateFormat("dd/M/yyyy, HH:mm", Locale.getDefault()).parse(temp);
					    String curStr = new SimpleDateFormat("dd/MM/yyyy, HH:mm",Locale.getDefault()).format(requestDate);
					    txt.setText(curStr);
					} catch (ParseException e) {
						e.printStackTrace();
					}
	        	}
	        	else if (tag == 2) {
	        		EditText txt = (EditText) findViewById(R.id.birth_date);
		            String temp = "" + date_picker.getDayOfMonth() + "/" + (date_picker.getMonth() + 1) + "/"
		                    + date_picker.getYear();
					try {
					    Date requestDate = new SimpleDateFormat("dd/M/yyyy", Locale.getDefault()).parse(temp);
					    String curStr = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(requestDate);
			            txt.setText(curStr);
					} catch (ParseException e) {
						e.printStackTrace();
					}
	        	}
	        	else if (tag == 0) {
	        		EditText txt = (EditText) findViewById(R.id.expires);
		            String temp = "" + date_picker.getDayOfMonth() + "/" + (date_picker.getMonth() + 1) + "/"
		                    + date_picker.getYear();
					try {
					    Date requestDate = new SimpleDateFormat("dd/M/yyyy", Locale.getDefault()).parse(temp);
					    String curStr = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(requestDate);
			            txt.setText(curStr);
					} catch (ParseException e) {
						e.printStackTrace();
					}
	        	}
	            dialog.cancel();
	        }
	     });
	} 
	
	public void setdateOnly(View v) {
		final Dialog dialog = new Dialog(this);
	    dialog.setContentView(R.layout.date_picker);
	    dialog.setCancelable(true);
	    dialog.setTitle("");
	    dialog.show();
	    	    
	    TimePicker time_picker = (TimePicker) dialog.findViewById(R.id.timePicker1);
	    time_picker.setVisibility(View.INVISIBLE);
	    
	    final DatePicker date_picker = (DatePicker) dialog.findViewById(R.id.datePicker1);
	    Button btn = (Button) dialog.findViewById(R.id.buttondatetime);
	    btn.setOnClickListener(new OnClickListener()
	    {
	        public void onClick(View arg0)
	        {
	        	if (tag == 2) {
	        		EditText txt = (EditText) findViewById(R.id.birth_date);
		            String temp = "" + date_picker.getDayOfMonth() + "/" + (date_picker.getMonth() + 1) + "/"
		                    + date_picker.getYear();
					try {
					    Date requestDate = new SimpleDateFormat("dd/M/yyyy", Locale.getDefault()).parse(temp);
					    String curStr = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(requestDate);
			            txt.setText(curStr);
					} catch (ParseException e) {
						e.printStackTrace();
					}
	        	}
	        	else if (tag == 0) {
	        		EditText txt = (EditText) findViewById(R.id.expires);
		            String temp = "" + date_picker.getDayOfMonth() + "/" + (date_picker.getMonth() + 1) + "/"
		                    + date_picker.getYear();
					try {
					    Date requestDate = new SimpleDateFormat("dd/M/yyyy", Locale.getDefault()).parse(temp);
					    String curStr = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(requestDate);
			            txt.setText(curStr);
					} catch (ParseException e) {
						e.printStackTrace();
					}
	        	}
	            dialog.cancel();
	        }
	     });
	} 
	
	@Override
	protected void onResume() {
		super.onResume();
		SetButtonActivity.getInstance().setRecognition(false);
		SetButtonActivity.getInstance().setButtons(this, showInfo,
				showServices, showGuide, showBooking, callout, callout_list,
				homeScreen, requests);
		try {
			int counter = RequestManager.getInstance().getRequestCount();
			this.counter.setText(""+counter);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    // manage message counter
	    if (this.counter.getText().equals("0")) 
	        this.counter.setVisibility(View.INVISIBLE);
	     else
	        this.counter.setVisibility(View.VISIBLE);
	}
		 
	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {		
		return super.onCreateOptionsMenu(GeneralUtils.createOptionsMenu(this, menu));
	}
	
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		GeneralUtils.onOptionsItemSelected(this, item);
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected Dialog onCreateDialog(final int id) {
		return GeneralUtils.createAboutUsDialog(this);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (action.equals("checkin")) 
			unbindDrawables(findViewById(R.id.checkin_relative));
		else
			unbindDrawables(findViewById(R.id.checkout_relative));
	    System.gc();  
	}
	
	private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
        	view.getBackground().setCallback(null);
        }
        
        if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            	unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }
}